import os
import time

from bson import ObjectId
from flask import Blueprint, request, send_file, jsonify
from setting import COVER_PATH, MUSIC_PATH, MONGODB, RET, CHAT_PATH
from my_ai import audio2text, my_nlp_lowB
from uuid import uuid4

uploader = Blueprint("uploader", __name__)


@uploader.route("/ai_uploader", methods=["POST"])
def ai_uploader():
	# 上传
	toy_id = request.form.get("toy_id")
	file_name = f"{uuid4()}.wav"
	file = request.files.get("reco")
	file_path = os.path.join(CHAT_PATH, file_name)
	file.save(file_path)
	# PCM 并且删除 原始wav文件
	os.system(f"ffmpeg -y  -i {file_path}  -acodec pcm_s16le -f s16le -ac 1 -ar 16000 {file_path}.pcm")
	os.remove(file_path)
	# 百度AI ASR
	Q = audio2text(file_path)
	# NLP
	ret = my_nlp_lowB(Q, toy_id)
	# TTS
	# 返回语音消息 返回音乐

	return jsonify(ret)


@uploader.route("/app_uploader", methods=["POST"])
def app_uploader():
	from_user = request.form.get("user_id")  # 发送方
	to_user = request.form.get("to_user")  # 接收方
	file = request.files.get("reco_file")  # 将amr文件转为Mp3？
	file_path = os.path.join(CHAT_PATH, file.filename)
	file.save(file_path)
	os.system(f"ffmpeg -i {file_path} {file_path}.mp3")
	os.remove(file_path)

	# 可能要存到数据库中
	chat_info = {
		"from_user": from_user,
		"to_user": to_user,
		"chat": f"{file.filename}.mp3",
		"createTime": time.time()
	}

	# chat = MONGODB.chats.find_one({"user_list":{"$all":[from_user,to_user]}})
	# chat["chat_list"].append(chat_info)

	MONGODB.chats.update_one({"user_list": {"$all": [from_user, to_user]}},
							 {"$push":{"chat_list":chat_info}})

	RET["CODE"] = 0
	RET["MSG"] = "好友列表查询"
	RET["DATA"] = {
		"filename": f"{file.filename}.mp3",
		"friend_type": "app"
	}

	return jsonify(RET)


@uploader.route("/toy_uploader", methods=["POST"])
def toy_uploader():
	print(request.form)
	print(request.files)
	# 语音文件保存

	# 将此条消息存放在 chat_list 中

	# 解释 - 为什么此实现之后，可以发送语音消息给App
	# 解释 - 为什么此实现之后，不可以发送语音消息给App

	return "200"



